package com.pixel.game.entity;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.pixel.game.Utils.PositionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class UnitManager {
    private final List<FriendlyUnit> friendlyUnits;
    private final List<EnemyUnit> enemyUnits;
    private final List<Unit> selectedUnits;
    private final List<Vector2> targetPositions;

    private static final float UNIT_SIZE = PositionUtils.getUnitSize();

    private int totalKillCount;

    private static final int MAX_ENEMY = 10;

    private static final int MAX_FRIENDLY = 10;

    public UnitManager() {
        friendlyUnits = new ArrayList<>();
        enemyUnits = new ArrayList<>();
        selectedUnits = new ArrayList<>();
        targetPositions = new ArrayList<>();
    }

    public void initializeUnits() {
        for (int i = 0; i < 5; i++) {
            addNewFriendlyUnit();
            addNewEnemyUnit();
        }
    }

    public void addNewFriendlyUnit() {
        float screenWidth = PositionUtils.getScreenWidth();
        float screenHeight = PositionUtils.getScreenHeight();
        float centerX = screenWidth / 2;
        float centerY = screenHeight / 2;

        float centerAreaWidth = 100.0f;
        float centerAreaHeight = 100.0f;

        float randomX = centerX - centerAreaWidth / 2 + (float) Math.random() * centerAreaWidth;
        float randomY = centerY - centerAreaHeight / 2 + (float) Math.random() * centerAreaHeight;
        Vector2 position = new Vector2(randomX, randomY);

        friendlyUnits.add(new FriendlyUnit(position, 10.0f, 100.0f, FriendlyUnit.ATTACK_COOLDOWN));
    }

    public void addNewEnemyUnit() {
        float screenWidth = PositionUtils.getScreenWidth();
        float screenHeight = PositionUtils.getScreenHeight();
        float centerX = screenWidth / 2;
        float centerY = screenHeight / 2;

        float restrictedAreaWidth = 200.0f;
        float restrictedAreaHeight = 200.0f;

        Vector2 position;
        int attempts = 0;
        int maxAttempts = 10;

        do {
            if (attempts >= maxAttempts) {
                System.err.println("Could not find a valid position for new enemy unit.");
                return;
            }
            position = PositionUtils.findRandomPosition(PositionUtils.getUnitPositions(enemyUnits), UNIT_SIZE);
            attempts++;
        } while (PositionUtils.isInRestrictedArea(position, centerX, centerY, restrictedAreaWidth, restrictedAreaHeight));

        Vector2 randomTarget = new Vector2(MathUtils.random(screenWidth), MathUtils.random(screenHeight));

        EnemyUnit enemyUnit = new EnemyUnit(position, getEnemyLevel());
        enemyUnit.setTargetPosition(randomTarget);
        enemyUnits.add(enemyUnit);
    }

    public void updateUnits(float deltaTime) {
        for (EnemyUnit enemy : enemyUnits) {
            Unit nearestFriendly = PositionUtils.findNearestTargetUnit(enemy, friendlyUnits);

            if (nearestFriendly != null) {
                float distanceToFriendly = enemy.getPosition().dst(nearestFriendly.getPosition());

                if (distanceToFriendly < EnemyUnit.APPROACH_RANGE) {
                    enemy.setTargetPosition(nearestFriendly.getPosition());
                } else {
                    enemy.updateRandomTargetPosition(deltaTime);
                }
            } else {
                enemy.updateRandomTargetPosition(deltaTime);
            }

            enemy.moveEnemyTowardsTarget(deltaTime);
        }

        PositionUtils.updateUnitPositions(selectedUnits, targetPositions, FriendlyUnit.UNIT_SPEED, deltaTime);
        processInteractions(System.currentTimeMillis());

        int spawn = 0;
        // 检查每个友军单位的等级，看看是否需要生成新单位
        for (FriendlyUnit friendlyUnit : friendlyUnits) {
            if (friendlyUnit.getSpawnNewUnit()) {
                // 创建一个新的友军单位（假设初始位置和属性）
                spawn++;
                friendlyUnit.setSpawnNewUnit(false);
            }
        }

        for (int i = 0; i < spawn && friendlyUnits.size() < MAX_FRIENDLY; i++) {
            System.out.println("New friendly unit spawned due to level up!");
            addNewFriendlyUnit();
        }


        if (enemyUnits.size() < MAX_ENEMY + getEnemyLevel()) {
            addNewEnemyUnit();
        }
    }


    /**
     * 交战逻辑
     *
     * @param currentTime 时间
     */
    public void processInteractions(long currentTime) {
        for (Iterator<EnemyUnit> enemyIterator = enemyUnits.iterator(); enemyIterator.hasNext(); ) {
            EnemyUnit enemyUnit = enemyIterator.next();

            for (Iterator<FriendlyUnit> friendlyIterator = friendlyUnits.iterator(); friendlyIterator.hasNext(); ) {
                FriendlyUnit friendlyUnit = friendlyIterator.next();

                if (friendlyUnit.getPosition().dst(enemyUnit.getPosition()) < friendlyUnit.getAttackRange()) {
                    if (friendlyUnit.canAttack(currentTime)) {
                        friendlyUnit.attack(enemyUnit, currentTime);

                        if (!enemyUnit.isAlive()) {
                            friendlyUnit.incrementKillCount(); // 增加击杀计数
                            incrementKillCount();
                            enemyIterator.remove();
                            break;
                        }
                    }
                }

                if (enemyUnit.getPosition().dst(friendlyUnit.getPosition()) < enemyUnit.getAttackRange()) {
                    if (enemyUnit.canAttack(currentTime)) {
                        enemyUnit.attack(friendlyUnit, currentTime);

                        if (!friendlyUnit.isAlive()) {
                            friendlyIterator.remove();
                        }
                    }
                }
            }
        }
    }

    public void drawUnits(ShapeRenderer shapeRenderer, BitmapFont font, SpriteBatch batch) {
        shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

        // 绘制友军单位
        shapeRenderer.setColor(Color.GREEN);
        for (FriendlyUnit unit : friendlyUnits) {
            // 检查单位是否被选中，如果是，标记为黄色
            if (selectedUnits.contains(unit)) {
                shapeRenderer.setColor(Color.YELLOW);
            } else {
                shapeRenderer.setColor(Color.GREEN);
            }
            Vector2 position = unit.getPosition();
            shapeRenderer.circle(position.x, position.y, UNIT_SIZE);
            drawHealthBar(shapeRenderer, unit);
            drawLevel(unit, font, batch);
            shapeRenderer.setColor(Color.GREEN);
        }

        // 绘制敌军单位
        shapeRenderer.setColor(Color.RED);
        for (Unit unit : enemyUnits) {
            Vector2 position = unit.getPosition();
            shapeRenderer.circle(position.x, position.y, UNIT_SIZE);
            drawHealthBar(shapeRenderer, unit);
            shapeRenderer.setColor(Color.RED);
        }

        shapeRenderer.end();

        // 在填充模式之后绘制线条模式
        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);

        // 绘制虚线连接

        drawConnectionLines(shapeRenderer);

        shapeRenderer.end();

        // 绘制击杀计数
        renderKillCount(font, batch);
    }

    /**
     * 绘制攻击路径
     */
    private void drawConnectionLines(ShapeRenderer shapeRenderer) {
        float preAttackRange = 10f;//预瞄范围
        shapeRenderer.setColor(Color.RED);
        for (EnemyUnit enemy : enemyUnits) {
            Unit target = PositionUtils.findNearestTargetUnit(enemy, friendlyUnits);
            if (target != null && enemy.getPosition().dst(target.getPosition()) < enemy.getAttackRange() + preAttackRange) {
                drawDottedLine(shapeRenderer, enemy.getPosition(), target.getPosition());
            }
        }
        shapeRenderer.setColor(Color.GREEN);
        for (FriendlyUnit friendly : friendlyUnits) {
            Unit target = PositionUtils.findNearestTargetUnit(friendly, enemyUnits);
            if (target != null && friendly.getPosition().dst(target.getPosition()) < friendly.getAttackRange() + preAttackRange) {
                drawDottedLine(shapeRenderer, friendly.getPosition(), target.getPosition());
            }
        }


    }

    /**
     * 绘制虚线
     */
    private void drawDottedLine(ShapeRenderer shapeRenderer, Vector2 start, Vector2 end) {
        float dashLength = 10f;
        float gapLength = 5f;
        float totalLength = start.dst(end);
        Vector2 direction = new Vector2(end).sub(start).nor();

        for (float i = 0; i < totalLength; i += dashLength + gapLength) {
            float segmentLength = Math.min(dashLength, totalLength - i);
            Vector2 segmentStart = new Vector2(start).mulAdd(direction, i);
            Vector2 segmentEnd = new Vector2(start).mulAdd(direction, i + segmentLength);
            shapeRenderer.line(segmentStart, segmentEnd);
        }
    }

    /**
     * 绘制血条
     */
    private void drawHealthBar(ShapeRenderer shapeRenderer, Unit unit) {
        float healthPercentage = unit.getHealth() / 100.0f;
        Vector2 position = unit.getPosition();
        float barWidth = 20.0f;
        float barHeight = 3.0f;

        shapeRenderer.setColor(Color.BLACK);
        shapeRenderer.rect(position.x - barWidth / 2, position.y + 6, barWidth, barHeight);

        shapeRenderer.setColor(Color.GREEN);
        shapeRenderer.rect(position.x - barWidth / 2, position.y + 6, barWidth * healthPercentage, barHeight);
    }

    public void drawLevel(FriendlyUnit friendlyUnit, BitmapFont font, SpriteBatch batch) {
        Vector2 position = friendlyUnit.getPosition();

        batch.begin();
        // 设置字体颜色
        font.setColor(Color.GOLD);
        // 绘制等级
        font.draw(batch, "Lv " + friendlyUnit.getLevel(), position.x - 10, position.y + 20);
        batch.end();
    }



    public void incrementKillCount() {
        this.totalKillCount++;
    }

    public int getEnemyLevel() {
        return this.totalKillCount / 10;
    }

    public void renderKillCount(BitmapFont font, SpriteBatch batch) {
        batch.begin();
        font.setColor(Color.WHITE);
        font.draw(batch, "Total Kills: " + totalKillCount, 10, Gdx.graphics.getHeight() - 10);
        font.draw(batch, "Enemy Level: " + getEnemyLevel(), 10, Gdx.graphics.getHeight() - 30);
        batch.end();
    }

    public void restartGame() {
        // 清除现有单位
        friendlyUnits.clear();
        enemyUnits.clear();

        // 重置游戏状态
        totalKillCount = 0;
    }

    public List<FriendlyUnit> getFriendlyUnits() {
        return friendlyUnits;
    }

    public List<Unit> getSelectedUnits() {
        return selectedUnits;
    }

    public List<Vector2> getTargetPositions() {
        return targetPositions;
    }
}
